//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent, Fragment } from 'react';
import { DndProvider, DragSource, DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
//import { getNodeByKeyAndCallbackProcess } from '@/components/_utils/algorithmTools';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Icon,
    Button,
    message,
    Divider,
    Table,
    Modal,
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import ProDictionarysTypeCreateForm from './ProDictionarysTypeCreateForm'; //新增类型
import ProDictionarysTypeUpdateForm from './ProDictionarysTypeUpdateForm'; //修改类型
import ProDictionarysTypeViewForm  from './ProDictionarysTypeViewForm'; //查看类型


import ProDictionarysListCreateForm from './ProDictionarysListCreateForm'; //新增字典列表
import ProDictionarysListUpdateForm from './ProDictionarysListUpdateForm'; //修改类型

import DictionarysTree  from './ProDictionarysTree'; //字典类型列表

import styles from './ProDictionarysList.less';
import {getValue} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { confirm } = Modal;
const { Search } = Input;

let dragingIndex = -1;

class BodyRow extends React.Component {
  render() {
    const { isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props;
    const style = { ...restProps.style, cursor: 'move' };

    let { className } = restProps;
    if (isOver) {
      if (restProps.index > dragingIndex) {
        className += ' drop-over-downward';
      }
      if (restProps.index < dragingIndex) {
        className += ' drop-over-upward';
      }
    }

    return connectDragSource(
      connectDropTarget(<tr {...restProps} className={className} style={style} />),
    );
  }
}


function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}
//字典项列表
class StandardTable extends PureComponent {
	
	constructor(props) {
	    super(props);
	    const { columns } = props;
	    const needTotalList = initTotalList(columns);
	
	    this.state = {
	      selectedRowKeys: [],
	      needTotalList,
	      data: [],
	    };
	}

	
	componentWillReceiveProps(nextProps) {
		if(undefined != nextProps.data && nextProps.data.list !== this.props.data.list) {
	      this.setState({data: nextProps.data.list});
		}
	}
	
	
	rowSource = {
	  beginDrag(props) {
	    dragingIndex = props.index;
	    return {
	      index: props.index,
	    };
	  },
	};

	rowTarget = {
	  drop(props, monitor) {
	    const dragIndex = monitor.getItem().index;
	    const hoverIndex = props.index;
	    if (dragIndex === hoverIndex) {
	      return;
	    }
	    props.moveRow(dragIndex, hoverIndex);
	    monitor.getItem().index = hoverIndex;
	  },
	};


	DragableBodyRow = DropTarget('row', this.rowTarget, (connect, monitor) => ({
	  connectDropTarget: connect.dropTarget(),
	  isOver: monitor.isOver(),
	}))(
	  DragSource('row', this.rowSource, connect => ({
	    connectDragSource: connect.dragSource(),
	  }))(BodyRow),
	);
	
	
	components = {
	    body: {
	      row: this.DragableBodyRow,
	    },
	};


	moveRow = (dragIndex, hoverIndex) => {
	    const { data } = this.state;
	    const dragRow = this.state.data[dragIndex];
	
	    this.setState(
	      update(this.state, {
	        data: {
	          $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
	        },
	      }),
	    );
	  };

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <DndProvider backend={HTML5Backend}>
	        <Table
	          rowKey={rowKey || 'key'}
	          rowSelection={rowSelection}
	          dataSource={this.state.data}
	          onRow={(record, index) => ({
	            index,
	            moveRow: this.moveRow,
	          })}
	          components={this.components}
	          pagination={paginationProps}
	          onChange={this.handleTableChange}
	          {...rest}
	          size="middle"
	        />
	    	</DndProvider>
      </div>
    );
  }
}


/* eslint react/no-multi-comp:0 */
@connect(({ prodictionarys, loading }) => ({
    prodictionarys,
    loading: loading.models.prodictionarys,
}))

@Form.create()
class ProDictionarysList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        
        modalVisibleByDict: false,
        updateModalVisibleByDict: false,
        updateFormValuesByDict: {},
        insertFormValuesByDict: {},
        dictId: "",
        dictData: [],
        addButtonVisible: 0,
        updateButtonVisible: 0,
        deleteButtonVisible: 0,
    };

    columns = [

        {
        title: '类型',
        dataIndex: 'dictid',
        key: 'dictid',
        },        {
        title: '常量名称',
        dataIndex: 'title',
        key: 'title',
        },        {
        title: '常量代码值',
        dataIndex: 'dictvalue',
        key: 'dictvalue',
        }, {
    		title: '操作',
    		align: 'center',
	        render: (text, record) => {
	        	const { updateButtonVisible,deleteButtonVisible } = this.state;
	        	return (
					<Fragment>
						{/*<a onClick={() => this.handleModalVisibleByDict(true,record)}>新增</a>
						<Divider type="vertical" />
					    <a onClick={() => this.handleUpdateModalVisibleByDict(true, record)}>修改</a>
					    <Divider type="vertical" />
					    <a onClick={() => this.handleDeleteRecordByDict(record)}>删除</a>*/}
						{updateButtonVisible == 1?(
					    	<Button  type="primary"  icon="edit" style={{marginRight: '5px'}} onClick={() => this.handleUpdateModalVisibleByDict(true,record)}></Button>
					    ):null}
					    {deleteButtonVisible == 1?(
					    	<Button  type="danger"  icon="delete" onClick={() => this.handleDeleteRecordByDict(true,record)}></Button>
					    ):null}
					    
				    </Fragment>
	        	)
	        }
		},
];


componentDidMount() {

    const { dispatch } = this.props;
    dispatch({
    	type: 'prodictionarys/query_page_for_prodictionarys',
    	payload: {
    		dictid:"",
    		currentPage: 1,
        	pageSize: 10,
    	}
    });
    
    dispatch({
    	type: 'prodictionarys/get_all_for_prodictionarys_type',
    	payload: {
    		description:""
    	}
    });
    
    dispatch({
    	type: 'prodictionarys/get_all_prodictionarys_type_by_select',
    	payload: {
    		description:""
    	}
    });
    
    
    if(localStorage.getItem('auth_button') == "undefined") return false;
    const authButton = JSON.parse(localStorage.getItem('auth_button'));
    getNodeByNameAndCallbackProcess(authButton,"prodictionarys",(item,index,arr) => {
    	if(item.children) {
    		item.children.map((item,index) => {
    			if(item.button_type == "add") {
    				this.setState({
    					addButtonVisible: 1,
    				})
    			}else if(item.button_type == "update") {
    				this.setState({
    					updateButtonVisible: 1,
    				})
    			}else if(item.button_type == "delete") {
    				this.setState({
    					deleteButtonVisible: 1,
    				})
    			}
    		})
    	}
    })
}


	componentWillReceiveProps(nextProps) {
		if(undefined != nextProps.prodictionarys.data && nextProps.prodictionarys.data.list !== this.props.prodictionarys.data.list) {
			
	      this.setState({dictData: nextProps.prodictionarys.data});
		}
	}

//字典项分页
handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,dictId } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
		    newObj[key] = getValue(filtersArg[key]);
		    return newObj;
		}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        dictid: dictId,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'prodictionarys/query_page_for_prodictionarys',
        payload: params,
    });
};


toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};

handleSelectRows = rows => {
    this.setState({
        selectedRows: rows,
    });
};

handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

		    const values = {
		        ...fieldsValue,
		        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
		    };
		
		    this.setState({
		        formValues: values,
		    });
		
		    dispatch({
		        type: 'prodictionarys/query_page_for_prodictionarys',
		        payload: values,
		    });
	});
};




handleModalVisible = flag => {
    this.setState({
        modalVisible: !!flag,
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

//新增字典类型
handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
        type: 'prodictionarys/insert_for_prodictionarys_type',
        payload: {
            title: fields.title,
        },
        callback: (res) => {
        	if(res.success) {
    			message.success('添加成功');
        	}else {
        		message.success('类型已存在请不要重复');
        	}
        }
    });

    this.handleModalVisible();

};

//修改字典类型
handleUpdate = fields => {

    const { dispatch } = this.props;
    dispatch({
        type: 'prodictionarys/update_for_prodictionarys_type',
        payload: {
            id: fields.id,
            title: fields.title,
        },
        callback: (res) => {
        	if(res.success) {
    			message.success('修改成功');
        	}else {
        		message.success('类型已存在请不要重复');
        	}
        }
    });
    this.handleUpdateModalVisible();

};

//删除字典类型
handleDeleteRecord = record => {
	const { dispatch } = this.props;
  confirm({
    title: '您确定要删除此类型吗?',
    okText: '确认',
    cancelText: '取消',
    onOk() {
        dispatch({
	        type: 'prodictionarys/delete_by_primarykey_for_prodictionarys_type',
	        payload: {
        		recordid: record.id,
	        },
	        callback: (res) => {
	        	if(res.success) {
	    			message.success('删除成功');
	        	}else {
	        		message.success('含有字典项不能删除');
	        	}
	        }
        });
    },
    onCancel() {},
  });
}

//根据字典类型查询字典项
checkedTreeChild = node => {
	const dictId = node.props.dataRef.dictid;
	const { dispatch } = this.props;
	dispatch({
        type: 'prodictionarys/query_page_for_prodictionarys',
        payload: {
        	dictid: dictId,
        	currentPage: 1,
        	pageSize: 10,
        }
	});
	this.setState({
		dictId: dictId,
	})
};





handleModalVisibleByDict = (flag,record) => {
    this.setState({
        modalVisibleByDict: !!flag,
        insertFormValuesByDict: record || {},
    });
};

handleUpdateModalVisibleByDict = (flag, record) => {
    this.setState({
        updateModalVisibleByDict: !!flag,
        updateFormValuesByDict: record || {},
    });
};


getNodeByKeyAndCallbackProcess (data, targetkey,callback) {
		for(let i = data.length - 1;i > -1;i--) {
			let item = data[i];
			if (item.key === targetkey) {
				callback(item, i, data);
   			}
				
			if (item.children) {
          		this.getNodeByKeyAndCallbackProcess(item.children, targetkey,callback);
        	}
		}
};

//新增字典项
handleAddByDict = fields => {
	const { dictData } = this.state;
	  
    const { dispatch } = this.props;
    dispatch({
        type: 'prodictionarys/insert_for_prodictionarys',
        payload: {
            dictid: fields.dictid,
            title: fields.title,
            parentvalue: fields.parentvalue,
        },
        callback: (res) => {
        	if(res.success) {
			   	this.getNodeByKeyAndCallbackProcess(dictData.list, fields.key,(item,i,data) => {
				   	data.unshift(res.datarecord);
				});
    			message.success('添加成功');
        	}else {
        		message.success('请不要重复添加');
        	}
        }
    });
    
    this.handleModalVisibleByDict();
};

//修改字典项
handleUpdateByDict = fields => {
	const { dictData } = this.state;
    const { dispatch } = this.props;
    dispatch({
        type: 'prodictionarys/update_for_prodictionarys',
        payload: {
            id: fields.id,
            dictid: fields.dictid,
            title: fields.title,
            dictvalue: fields.dictvalue,
        },
        callback: (res) => {
        	if(res.success) {
        		this.getNodeByKeyAndCallbackProcess(dictData.list, fields.key,(item,i,data) => {
					   	data[i].title = fields.title;
				});
    			message.success('修改成功');
        	}else {
        		message.success('请不要重复添加');
        	}
        }
    });
    
    this.handleUpdateModalVisibleByDict();

};

//删除字典项
handleDeleteRecordByDict = record => {
		const { dictData } = this.state;
		const { dispatch } = this.props;
		const _this = this;
	  confirm({
	    title: '您确定要删除此字典项吗?',
	    okText: '确认',
	    cancelText: '取消',
	    onOk() {
	        dispatch({
		        type: 'prodictionarys/delete_by_primarykey_for_prodictionarys',
		        payload: {
	        		recordid: record.id,
	        		dictid: record.dictid,
		        },
		        callback: (res) => {
		        	if(res.success) {
		        		_this.getNodeByKeyAndCallbackProcess(dictData.list, record.key,(item,i,data) => {
					   			data.splice(i,1);
					  		});
		    				message.success('删除成功');
		        	}else {
		        		message.success('含有字典项不能删除');
		        	}
		        }
	        });
	    },
	    onCancel() {},
	  });
};



	onSearch = value => {
		const { dispatch } = this.props;
		dispatch({
	        type: 'prodictionarys/query_page_for_prodictionarys',
	        payload:{
	        	title: value,
	        },
	        callback: (response) => {
	        	
	        }
	  	});
	};


renderSimpleForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
        <FormItem label="类型">
        {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="常量显示名称">
        {getFieldDecorator('name')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        展开 <Icon type="down" />
        </a>
        </span>
        </Col>
        </Row>
        </Form>
);
}

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
        <FormItem label="类型">
        {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="常量显示名称">
        {getFieldDecorator('name')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    <Col md={8} sm={24}>
        <FormItem label="常量代码值">
        {getFieldDecorator('value')(<Input placeholder="请输入" />)}
</FormItem>
    </Col>
    </Row>
    <div style={{ overflow: 'hidden' }}>
<div style={{ marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        收起 <Icon type="up" />
        </a>
        </div>
        </div>
        </Form>
);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            prodictionarys: { data,dictionarysTree,dictionarysTypeBySelect,cascaderList },
            loading,
        } = this.props;

        const { 
        	selectedRows, 
        	modalVisible, 
        	updateModalVisible, 
        	viewModalVisible,  
        	updateFormValues,  
        	viewFormValues,
        	
        	modalVisibleByDict,
        	updateModalVisibleByDict,
        	updateFormValuesByDict,
        	insertFormValuesByDict,
        	dictData,
        	addButtonVisible
        } = this.state;
        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
        };
        const updateMethods = {
            handleUpdateModalVisible: this.handleUpdateModalVisible,
            handleUpdate: this.handleUpdate,
        };
        const viewMethods = {
            handleViewModalVisible: this.handleViewModalVisible
        };
        
        const parentRole = {
	       	selectedRows: selectedRows,
	       	handleModalVisible: this.handleModalVisible,
	       	handleUpdateModalVisible: this.handleUpdateModalVisible,
	       	handleViewModalVisible: this.handleViewModalVisible,
	       	handleDeleteRecord: this.handleDeleteRecord,
	       	checkedTreeChild: this.checkedTreeChild,
	       	dispatch: this.props.dispatch,
	    };
		    
		const parentMethodsByDict = {
            handleAddByDict: this.handleAddByDict,
            handleModalVisibleByDict: this.handleModalVisibleByDict,
            dictionarysTypeBySelect,
            dispatch: this.props.dispatch,
            cascaderList,
        };
        const updateMethodsByDict = {
            handleUpdateModalVisibleByDict: this.handleUpdateModalVisibleByDict,
            handleUpdateByDict: this.handleUpdateByDict,
        };
        
        return (
            <PageHeaderWrapper title="字典信息列表">
            <Card bordered={false} style={{width: '25%',float: 'left'}}>
				{dictionarysTree && Object.keys(dictionarysTree).length ? (
	        	<DictionarysTree {...parentRole} menu={dictionarysTree}/>
	        	) : null}
            </Card>
            <Card bordered={false} style={{width: '73%',float: 'right'}}>
            <div className={styles.proDictionarystableList}>
            {/*<div className={styles.proDictionarystableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.proDictionarystableListOperator}>
                {addButtonVisible == 1?(
		            <Button icon="plus" type="primary" onClick={() => this.handleModalVisibleByDict(true)}>
		        	新增
		        	</Button>
        		):null}

    </div>
				{/*<Search style={{ marginBottom: 8 }} placeholder="请输入常量名称" onSearch={this.onSearch} />*/}
        <StandardTable
        rowKey={"id"}
        selectedRows={selectedRows}
        loading={loading}
        data={dictData}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>
	
        <ProDictionarysTypeCreateForm {...parentMethods} modalVisible={modalVisible} />
        <ProDictionarysListCreateForm {...parentMethodsByDict} modalVisibleByDict={modalVisibleByDict} values={insertFormValuesByDict} />
        
        {updateFormValues && Object.keys(updateFormValues).length ? (
            <ProDictionarysTypeUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}
        
        {updateFormValuesByDict && Object.keys(updateFormValuesByDict).length ? (
            <ProDictionarysListUpdateForm
            {...updateMethodsByDict}
            updateModalVisibleByDict={updateModalVisibleByDict}
            values={updateFormValuesByDict}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ProDictionarysTypeViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
    }
}

export default ProDictionarysList;
